import React, { useCallback, useEffect, useMemo, useState } from "react";
import HeaderInput from "./HeaderInput";
import FooterControl from "./FooterControl";
import { ListStyle } from "./style/listStyle";

export default function TodoList() {
  //   let num = 1;
  //  const [变量, 更新变量的函数] = useState(1);
  const [list, setList] = useState([
    { id: 1, name: "jack", address: "北京", checked: false },
  ]);

  useEffect(() => {
    console.log("函数已加载");
    console.log("更新");
    return () => {
      //卸载
      console.log("已卸载");
    };
  }, [list]);

  //统计已添加的任务条数
  const len = useMemo(() => {
    return list.length;
  }, [list]);

  //点击按钮添加
  const add = useCallback(
    (obj) => {
      console.log("obj:::", obj);
      setList([...list, obj]);
    },
    [list]
  );
  const getIndex = (id) => {
    return list.findIndex((item) => {
      return item.id === id;
    });
  };

  //删除某一项
  const deleteItem = (id) => {
    const index = getIndex(id);
    list.splice(index, 1);
    setList([...list]);
  };

  return (
    <div className="todo">
      {/* 输入框 */}
      <HeaderInput add={add} aa="1" bb="2"></HeaderInput>
      {/* 列表 */}
      <div className="box">
        {list.length > 0 ? (
          <ListStyle>
            {list.map((item) => {
              return (
                <li key={item.id}>
                  {item.name}
                  <button
                    style={{ marginLeft: 30 }}
                    onClick={() => deleteItem(item.id)}
                  >
                    删除
                  </button>
                </li>
              );
            })}
          </ListStyle>
        ) : (
          <div>没有数据了</div>
        )}
      </div>
      {/* 底部footer  */}
      <FooterControl len={len}></FooterControl>
    </div>
  );
}
